#========================================================
#============= auth_manage_group_auth.py ================
#========================================================
#  -written by HitThePipe
#  --for group_auth
#
#
# This subscript of group_auth allows you to edit your es_group_auth.sqldb
# from game chat. You can add/remove groups, move users to and from groups,
# change a groups capabilities, etc., just about anything you can do with 
# the gauth server commands. If there's anything I've missed, please let me know.
#
# *******************************************************
# For obvious reasons I STRONGLY suggest you DON'T 
# give this scripts capabilities to many admins.  
# The fewer and most trusted the better.
# *******************************************************
#
# There are only 2 chat commands:
#  - !auth  ->Brings up main Auth Management menu
#  - !addgroup <GroupName> <AccessLevel>
#    Ex. !addgroup MyGroup poweruser
#     -Accepted Access Levels ->in order of most powerful to least:
#      - root, admin, poweruser, known, all  ->Careful with root
#
#  Installation:
#   - Place in addons/eventscripts/examples/auth/group_auth/auth_manage_group_auth
#   - Edit autoexec.cfg
#    - es_load examples/auth/group_auth
#    - es_load examples/auth/group_auth/auth_manage_group_auth
#
#
# If you've never run the group_auth service before, you need to 
# do a few things to get started. This script will not work until
# you've done the following. If you already have group_auth setup,
# you don't need to do the following setup. 
#
# *****************************************************************
# *** ALL OF THE FOLLOWING COMMANDS MUST BE RUN THROUGH CONSOLE ***
# *****************************************************************
#
# -First you'll want to create a new group with admin level access 
#  to be able to run any commands from scripts that require admin 
#  access, including this one. To do this,
#  use the following command:
#
#  - es gauth group create <GroupName> server_var(AUTHSERVICE_ADMIN)
#
#    Ex. es gauth group create "Admins" server_var(AUTHSERVICE_ADMIN)
#
#       - The AUTHSERVICE_ADMIN is what sets this groups default level access.
#        -other accepted AUTHSERVICE_* are:
#         - POWERUSER, IDENTIFIED, UNRESTRICTED, ROOT
#
# -After you've created your group, you'll want to give the auth_management 
#  and add_group capabilities to it. Use the following for this:
# 
#  - gauth power give "auth_management" "<GroupName>"
#    gauth power give "add_group" "<GroupName>" 
#
#    Ex. gauth power give "auth_management" "Admins" 
#
# -Now you need to add yourself to group_auths' database. Do that with the following:
#            
#  - gauth user create "<your name>" "<steam id>"
#
#    Ex. gauth user create "HitThePipe" "STEAM_0:0:XXXXXXX"
#
# -Lastly you need to add yourself to the group you created above:
#
#  - gauth user join "<your name>" "<GroupName>"
#
#    Ex. gauth user join "HitThePipe" "Admins"
#
#============ DO NOT EDIT ANYTHING IN THIS SCRIPT ==============
#================ THERE ARE NO USER SETTINGS ===================

import es
import services
import popuplib
import sqlite3

auth = services.use('auth')
con = sqlite3.connect(es.getAddonPath('examples/auth/group_auth/') + 'es_group_auth.sqldb')
cur = con.cursor()
gUserGroups = {}

def load():
	es.regsaycmd('!auth','examples/auth/group_auth/auth_manage_group_auth/send_main')
	auth.registerCapability('auth_management',auth.ADMIN)
	
	es.regsaycmd('!addgroup','examples/auth/group_auth/auth_manage_group_auth/add_group')
	auth.registerCapability('add_group',auth.ADMIN)
	
	es.regcmd('addgroup','examples/auth/group_auth/auth_manage_group_auth/add_group','addgroup')
	
	auth_manage_menu = popuplib.create('auth_manage_menu')
	auth_manage_menu.addline('Authorization Management:')
	auth_manage_menu.addline(' -choose a task:')
	auth_manage_menu.addline('-------------------------')
	auth_manage_menu.addline('->1. Current Players')
	auth_manage_menu.addline('->2. Groups')
	auth_manage_menu.addline('->3. Users')
	auth_manage_menu.addline('->4. Capabilities')
	auth_manage_menu.addline('-------------------------')
	auth_manage_menu.addline('0. Close')
	auth_manage_menu.submenu(1,'player_menu')
	auth_manage_menu.submenu(2,'groups_menu_main')
	auth_manage_menu.select(3,'examples/auth/group_auth/auth_manage_group_auth/users_menu')
	auth_manage_menu.select(4,'examples/auth/group_auth/auth_manage_group_auth/caps_menu')
	
	groups_menu_main = popuplib.create('groups_menu_main')
	groups_menu_main.addline('Manage Groups')
	groups_menu_main.addline('---------------')
	groups_menu_main.addline('->1. Groups Users')
	groups_menu_main.addline('->2. Groups Capabilities')
	groups_menu_main.addline('->3. Add a new Group')
	groups_menu_main.addline('->4. Remove a Group')
	groups_menu_main.addline('-----------------')
	groups_menu_main.addline('9. Main Menu')
	groups_menu_main.addline('0. Close')
	groups_menu_main.select(1,'examples/auth/group_auth/auth_manage_group_auth/group_users_list')
	groups_menu_main.select(2,'examples/auth/group_auth/auth_manage_group_auth/group_caps_list')
	groups_menu_main.submenu(3,'add_group_menu')
	groups_menu_main.select(4,'examples/auth/group_auth/auth_manage_group_auth/remove_group')
	groups_menu_main.submenu(9,'auth_manage_menu')
	
	cap_menu = popuplib.create('cap_menu')
	cap_menu.addline('Manage Capability')
	cap_menu.addline('-------------------')
	cap_menu.addline('->1. Capability groups')
	cap_menu.addline('->2. Add Cap to group')
	cap_menu.addline('->3. Remove Cap from group')
	cap_menu.addline('------------------------')
	cap_menu.addline('8. Previous')
	cap_menu.addline('9. Main Menu')
	cap_menu.addline('0. Close')
	cap_menu.select(1,'examples/auth/group_auth/auth_manage_group_auth/cap_groups_list')
	cap_menu.select(2,'examples/auth/group_auth/auth_manage_group_auth/cap_group_add_menu')
	cap_menu.select(3,'examples/auth/group_auth/auth_manage_group_auth/cap_group_remove_menu')
	cap_menu.select(8,'examples/auth/group_auth/auth_manage_group_auth/caps_menu')
	cap_menu.submenu(9,'auth_manage_menu')
	
	remove_cap_menu = popuplib.create('remove_cap_menu')
	remove_cap_menu.addline('Remove cap from blah')
	remove_cap_menu.addline('--------------------')
	remove_cap_menu.addline('->1. Yes')
	remove_cap_menu.addline('->2. No')
	remove_cap_menu.addline('--------------------')
	remove_cap_menu.addline('9. Previous Menu')
	remove_cap_menu.addline('0. Close')
	remove_cap_menu.menuselect = examples/auth/group_auth/auth_manage_group_auth/group_cap_remove
	
	add_group_menu = popuplib.create('add_group_menu')
	add_group_menu.addline('Add Group chat command')
	add_group_menu.addline(' -<Syntax>-')
	add_group_menu.addline('----------------------')
	add_group_menu.addline('->!addgroup <GroupName> <GroupType>')
	add_group_menu.addline('Ex. !addgroup MyGroup admin')
	add_group_menu.addline('---------------------------------')
	add_group_menu.addline('-No space in GroupName')
	add_group_menu.addline('-Accepted GroupTypes:')
	add_group_menu.addline(' - admin') #GDefaultLevel=1
	add_group_menu.addline(' - poweruser') #GDefaultLevel=2
	add_group_menu.addline(' - known') #Actually _IDENTIFIED GDefaultLevel=4
	add_group_menu.addline(' - all') #Actually _UNRESTRICTED GDefaultLevel=128
	add_group_menu.addline(' - root (CAUTION!)') #GDefaultLevel=0
	add_group_menu.addline('----------------------')
	add_group_menu.addline('0. Close')
	
	users_submenu = popuplib.create('users_submenu')
	users_submenu.addline('BLAH')
	users_submenu.addline('------------------')
	users_submenu.addline('->1. Drop user from a group')
	users_submenu.addline('->2. Add user to a group')
	users_submenu.addline('->3. Drop user from all groups')
	users_submenu.addline('----------------------------')
	users_submenu.addline('->8. Previous Menu')
	users_submenu.addline('->9. Main Menu')
	users_submenu.addline('------------')
	users_submenu.addline('0. Close')
	users_submenu.select(1,'examples/auth/group_auth/auth_manage_group_auth/user_in_groups')
	users_submenu.select(2,'examples/auth/group_auth/auth_manage_group_auth/user_notin_groups')
	users_submenu.select(3,'examples/auth/group_auth/auth_manage_group_auth/user_allgroup_remove')
	users_submenu.submenu(8,'users_groups_menu1')
	users_submenu.submenu(9,'auth_manage_menu')
	
	player_menu = popuplib.construct("player_menu","players","#human")
    player_menu.menuselectfb = manage_player
    player_menu.settitle('Player List')

def send_main():
    userid = es.getcmduserid()
    if auth.isUseridAuthorized('userid',auth_management):
        popuplib.send('auth_manage_menu',userid)
    else:
        es.tell(userid,'#green[Auth Manage] You do not have permission to use the !auth command')

def manage_player(userid,choice,popupid):
    if popuplib.exists('groups_menu'):
        popuplib.delete('groups_menu')
    groups_menu = popuplib.easymenu('groups_menu',None,set_player_group)
    groups_menu.settitle('%s\n-Add player to group' %es.getplayername(choice))
    groups_menu.submenu('player_menu')
    group_list_menu(userid,groups_menu)
    gUserGroups[userid] = choice

def set_player_group(userid,choice,popupid):
    es.server.cmd('gauth user join '+es.getplayername(gUserGroups[userid])+' '+choice)
	popuplib.send('groups_menu',userid)
	del gUserGroups[userid]

def add_group():
    (group,caplevel) = es.getargs().split()
    if (caplevel == 'KNOWN') or (caplevel == 'known'):
        level = str(auth.IDENTIFIED)
    elif (caplevel == 'ALL') or (caplevel == 'all'):
        level = str(auth.UNRESTRICTED)
    es.server.cmd('gauth group create '+group+' '+level)

def group_users_list(userid,choice,popupid):
    if popuplib.exists('groups_menu'):
        popuplib.delete('groups_menu')
    groups_menu = popuplib.easymenu('groups_menu',None,group_users)
    groups_menu.settitle("Groups\n-select for a Group's users")
    groups_menu.submenu('groups_menu_main')
    group_list_menu(userid,groups_menu)

def group_caps_list(userid,choice,popupid):
    if popuplib.exists('groups_menu'):
        popuplib.delete('groups_menu')
    groups_menu = popuplib.easymenu('groups_menu',None,group_caps)
    groups_menu.settitle("Groups\n-select for a Group's caps")
    groups_menu.submenu('groups_menu_main')
    group_list_menu(userid,groups_menu)

def remove_group(userid,choice,popupid):
    if popuplib.exists('groups_menu'):
        popuplib.delete('groups_menu')
    groups_menu = popuplib.easymenu('groups_menu',None,group_users)
    groups_menu.settitle("Groups\n-select to remove a group")
    groups_menu.submenu('groups_menu_main')
    group_list_menu(userid,groups_menu)

def group_list_menu(userid,popup):
    query = cur.execute("SELECT GroupName FROM Groups WHERE GroupName!='UnidentifiedPlayers' and GroupName!='IdentifiedPlayers';")
    if query:
        query = cur.execute("SELECT GroupName FROM Groups WHERE GroupName!='UnidentifiedPlayers' and GroupName!='IdentifiedPlayers';")
        for (group,) in query:
            groups_menu.addoption(group,group)
        popuplib.send('groups_menu',userid)
    else:
        es.tell(userid,'#multi','#green[AuthService]#lightgreen There are no custom groups.')
        popuplib.send('auth_manage_menu',userid)

def group_users(userid,choice,popupid):
    if popuplib.exists('group_users_menu'):
        popuplib.delete('group_users_menu')
    query = cur.execute("SELECT ALL Name FROM vwPlayersGroups WHERE GroupName='?'",(choice,))
    if query:
    	group_users_menu = popuplib.easymenu('group_users_menu',None,group_user_remove)
        group_users_menu.settitle(choice+' Users:\n -select to remove')
        group_users_menu.submenu('groups_menu')
        for (name,) in query:
    	    group_users_menu.addoption(name,name)
    	popuplib.send('group_users_menu',userid)
    else:
        es.tell(userid,'#multi','multi #green [AuthService] #lightgreen There are no users in '+choice)
    

def group_caps(userid,choice,popupid):
    pass